const jwt = require('jsonwebtoken')
const md5 = require('md5')
const svgCaptcha = require('svg-captcha');
const { mysqlApi } = require('../model/db')
const messageInfo = require('../utils/messageInfo')
let captchaText = null;
exports.Login = async (req, res) => {
    const { username, password, level, captcha } = req.body
    console.log(req.body);
    const sqlStr = `SELECT * FROM users where username = '${username}';`
    try {
        const data = (await mysqlApi(sqlStr))[0];
        if (captcha.toLowerCase() != captchaText) {
            return res.status(400).json(messageInfo(null, '400', '验证码不正确'))
        }
        if (!data || data.level != level) {
            return res.status(400).json(messageInfo(null, '400', '没有找到该用户'))
        }
        if (data.password != md5(password)) {
            return res.status(400).json(messageInfo(null, '403', '密码不正确'))
        }
        //生成token
        const token = jwt.sign(
            {
                data: data, //需要放到token的参数
                user_id: data.user_id,
                level: level
            },
            'huohua29', //随便一点内容，加密的密文，私钥对应着公钥
            {
                expiresIn: 60 * 60 * 24 //60分钟到期时间
            }
        )
        res.status(200).json(messageInfo({ ...data, token: token }, '200', '登陆成功'))
    } catch (error) {
        res.status(400).json(messageInfo(error, '400', '登陆失败'))
    }
}

exports.Logout = async (req, res) => {
    res.status(200).json(messageInfo(null, '200', '请移除token'))
}

exports.Captcha = async (req, res) => {
    const captcha = svgCaptcha.create({
        size: 4,
        ignoreChars: '0o1i',
        noise: 6,
        color: true,
        background: '#a1c4fda7',
    })
    captchaText = captcha.text.toLowerCase();
    res.type('svg');
    res.status(200).send(captcha.data)
}

